const createError = require("http-errors");
const multer = require('multer')

// 没找到该条数据资源
// class NotFountError extends Error {
//     constructor(message) {
//         super(message)
//         this.name = 'NotFountError'
//     }
// }

function success(res, msg, data = {}, code = 200) {
  res.json({
    code,
    data,
    msg: msg || "success",
  });
}
function fail(res, error, code = 500) {
  // sequelize抛出的字段参数错误
  if (
    error.name === "SequelizeValidationError" ||
    error.name === "SequelizeUniqueConstraintError" ||
    error.name === "ValidationError"
  ) {
    res.status(400).json({
      code: 400,
      data: null,
      msg: error.errors[0].message,
    });
  }
  // multer上传错误
  else if (error instanceof multer.MulterError) {
    res.status(error.status || 400).json({
      code: error.status || 400,
      message: error.name + ": " + error.message,
    });
  } 
  // http-errors错误
  else if (error instanceof createError.HttpError) {
    res.status(error.status).json({
      code: error.status,
      message: error.name + ": " + error.message,
    });
  }
  // 其他服务端错误
  else {
    console.log(error);
    res.status(500).json({
      code: code,
      data: null,
      msg: error.message,
    });
  }
}
module.exports = {
  success,
  fail,
};
